<?php

declare(strict_types=1);

namespace app\api\controller;

use think\facade\Request;
use think\facade\Db;
use app\api\controller\WxpayService;
use app\api\controller\Withdrawal;
use app\api\service\UserService;
use app\model\zs\ZsMemberCoupon;
use app\model\zs\ZsMemberCouponProvide;
use app\model\zs\ZsMemberMeal;
use app\model\zs\ZsMemberPlugDraw;
use app\model\zs\ZsMemberPlugDrawNum;
use think\facade\Filesystem;
use think\file\UploadedFile;
use app\model\zsnew\ZsnewKcSale;
use app\repository\CouponRepository;

/**
 * 店庆抽奖
 * Class PlugAnni
 * @package app\api\controller
 */
class PlugAnni
{
    /**
     * 抽奖配置
     * @return false|string
     */
    public function getConfig()
    {
        $set_id = Request::param('set_id');
        $set_id = $set_id ?: 1;
        $rs = Db::connect('zs')->table('member_plug_draw_set')->where('id', $set_id)->find();

        // 控制领券说明文字显示或隐藏
        $rs['textHide'] = false;
        if( $set_id == 11) { // 满额礼
            $rs['textHide'] = true;
        }
        if ($set_id == 12) { // 新人礼
            $rs['textHide'] = true;
        }
        return $rs;
    }

    public function userDaySaleV2()
    {
        // 活动已下线，强制返回剩余抽奖次数为0
        $draw_num_wait = 0;
        return jsonData(1, 'ok', compact('draw_num_wait'));

        $vipcode = Request::param('vipcode');
        $mobile = Request::param('mobile');
        $project_type = Request::param('project_type') ?: 3;

        $time = time();
        $today = date('Y-m-d', $time);

        $this->autoAddDrawNum($vipcode, $mobile);

        $draw_num_wait = $this->drawNumWait($vipcode, $today);
        return jsonData(1, 'ok', compact('draw_num_wait'));
    }

    public function userDaySaleAble()
    {
        $vipcode = Request::param('vipcode');
        $mobile = Request::param('mobile');

        $time = time();
        $today = date('Y-m-d', $time);

        $draw_num_wait = $this->drawNumWait($vipcode, $today);
        return jsonData(1, 'ok', compact('draw_num_wait'));
    }

    /**
     * 计算当天销售数据并写入抽奖次数表
     */
    public function autoAddDrawNum($vipcode, $mobile)
    {
        $time = time();
        $today = date('Y-m-d', $time);
        $startDate = date('Y-m-d 00:00:00', $time);
        $endDate = date('Y-m-d 23:59:59', $time);
        $endDateMonth = date('Y-m-t 23:59:59', $time);

        // 百货会员单笔实付满300即可参与刮刮卡，单笔最高抽3次，百分百有奖。
        // 单个会员单日限刮6次
        $luck_num_sale = 0;
        $saleList = ZsnewKcSale::where('XF_VIPCODE', $vipcode)
            ->whereBetweenTime('XF_CREATETIME', $startDate, $endDate)
            ->select();
        foreach ($saleList as $saleItem) {
            if ($saleItem['XF_SELLINGAMOUNT'] >= 300 && $saleItem['btype'] == 2) {
                $luck_num_sale += min(intval($saleItem['XF_SELLINGAMOUNT'] / 300), ZsMemberPlugDrawNum::LUCK_NUM_PER_MAX);
            }
        }
        $luck_num_sale = min($luck_num_sale, ZsMemberPlugDrawNum::LUCK_NUM_MAX);

        $draw_num_sale =  $this->drawNumSale($vipcode, $today);
        $draw_num =  $this->drawNum($vipcode, $today);

        // 待新增的次数
        $draw_num_add = $luck_num_sale - $draw_num_sale;
        $draw_num_add = min(ZsMemberPlugDrawNum::LUCK_NUM_MAX - $draw_num, $draw_num_add);
        $this->addDrawNum($vipcode, $mobile, $draw_num_add);
    }

    /**
     * 用户当天总共抽奖的次数
     */
    public function drawNum($vipcode, $today)
    {
        return ZsMemberPlugDrawNum::where('vipcode', $vipcode)->where('today', $today)->count();
    }

    /**
     * 用户当天还能够抽奖的次数
     */
    public function drawNumWait($vipcode, $today)
    {
        return ZsMemberPlugDrawNum::where('vipcode', $vipcode)->where('today', $today)->where('use_status', 0)->count();
    }

    /**
     * 给用户增加抽奖次数
     */
    public function addDrawNum($vipcode, $mobile, $num, $source = 1)
    {
        $time = time();
        $today = date('Y-m-d', $time);

        for ($i = 1; $i <= $num; $i++) {
            // `source`  '来源类型，1：消费获得，2：手动推送次数'
            $model_draw_num = new ZsMemberPlugDrawNum();
            $model_draw_num->vipcode = $vipcode;
            $model_draw_num->mobile = $mobile;
            $model_draw_num->today = $today;
            $model_draw_num->source = $source;
            $model_draw_num->save();
        }
    }

    /**
     * 用户当天消费获得的抽奖的次数
     */
    private function drawNumSale($vipcode, $today)
    {
        return ZsMemberPlugDrawNum::where('vipcode', $vipcode)->where('today', $today)->where('source', 1)->count();
    }

    private function drawNumUsed($vipcode, $today)
    {
        $model = ZsMemberPlugDrawNum::where('vipcode', $vipcode)->where('today', $today)->where('use_status', 0)->find();
        if (!$model) {
            return false;
        }
        $model->use_status = 1;
        $model->use_time = date('Y-m-d H:i:s');
        $model->save();
        return true;
    }

    /**
     * 查询会员销售
     * @return false|string
     */
    public function userDaySale()
    {
        $vipcode = Request::param('vipcode');
        $project_type = Request::param('project_type') ?: 3;

        //$vipcode = '000001150320';
        $startDate = date('Y-m-d 00:00:00',time());
        $endDate = date('Y-m-d 23:59:59',time());
        $endDateMonth = date('Y-m-t 23:59:59', time());
        $saleList = ZsnewKcSale::where('XF_VIPCODE' , $vipcode)
            ->whereBetweenTime('XF_CREATETIME', $startDate, $endDate)
            ->select();
        $luckIn = 0;
        foreach ($saleList as $key=>$value){
            if($value['XF_SELLINGAMOUNT']>=200){
                //查询已经抽取次数 member_luck_log,luckname,set_id
                $luckcount = Db::connect('zs')->table("member_luck_log")->where(['vipcode'=>$vipcode,'set_id'=>$project_type])
                    ->whereBetweenTime('create_at', $startDate, $endDateMonth)
                    ->count();
                $daycount = Db::connect('zs')->table("member_luck_log")
                    ->where(['vipcode'=>$vipcode,'set_id'=>$project_type])
                    ->whereBetweenTime('create_at', $startDate, $endDate)
                    ->count();
                if($luckcount<2 && $daycount<1){
                    //可以参与抽奖
                    $luckIn = 1;
                    break;
                }
            }
        }
        return jsonData(1, '查询成功', $luckIn);
    }

    /**
     * 查询奖品
     * @return false|string
     */
    public function drawList()
    {
        //fonts: [{ text: item, top: '10%' }],
        //imgs:[{ src: `./img/${index}.png`, width: '30%', top: '35%' }],
/*        [
          { title: '1元红包', background: '#f9e3bb', fonts: [{ text: '1元红包', top: '18%' }] },
          { title: '100元红包', background: '#f8d384', fonts: [{ text: '100元红包', top: '18%' }] },
          { title: '0.5元红包', background: '#f9e3bb', fonts: [{ text: '0.5元红包', top: '18%' }] },
          { title: '2元红包', background: '#f8d384', fonts: [{ text: '2元红包', top: '18%' }] },
          { title: '10元红包', background: '#f9e3bb', fonts: [{ text: '10元红包', top: '18%' }] },
          { title: '50元红包', background: '#f8d384', fonts: [{ text: '50元红包', top: '18%' }] },
        ]*/

        $project_type = Request::param('project_type');
        $project_type = $project_type ?: 0;

        $list = Db::connect('zs')->table("member_plug_draw")->field('title,background,text,top,imgs,id,luck')->where(['status'=>1, 'project_type' => $project_type])->select();
        //$arr = [];
        foreach ($list as $v){
            if ($project_type == 0) {
                $arr[] = [
                    'title' => $v['title'],
                    'background' => $v['background'],
                    'fonts' => [[
                        'text' => $v['text'],
                        'top' => $v['top'],
                    ]],
                    'imgs' =>[[
                        'src' => $v['imgs'],
                        'width' => '16%',
                        'top' => '35%'
                    ]],
                    'id' => $v['id'],
                    'luck' => $v['luck']
                ];
            } else {
                $arr[] = [
                    'title' => $v['title'],
                    'background' => $v['background'],
                    'fonts' => [[
                        'text' => $v['text'],
                        'top' => $v['top'],
                        // 'fontSize' => '26px',
                    ]],
                    // 'imgs' =>[[
                    //     'src' => $v['imgs'],
                    //     'width' => '16%',
                    //     'top' => '35%'
                    // ]],
                    'id' => $v['id'],
                    'luck' => $v['luck']
                ];
            }

        }

        return json_encode($arr);
        //return jsonData(1, '成功', $arr);
    }

    /**
     * 获取抽奖结果
     * @return false|string
     */
    public function getLuck()
    {
        $project_type = Request::param('project_type');
        $project_type = $project_type ?: 0;

        $list = Db::connect('zs')->table("member_plug_draw")->field('id,title,background,text,top,imgs,probability,number')->where(['status'=>1, 'project_type' => $project_type])->order('id', 'desc')->select();

        foreach ($list as $v){
            $luckCount = Db::connect('zs')->table("member_luck_log")->where(['luckname'=>$v['id']])->count();
            if($luckCount>=$v['number']){
                continue;
            }
            $arr[] = $v;
        }
        $data = $this->get_rand($arr);

        return $data;
    }

    public function get_rand($proArr) {
        $result = '';
        //array_column($proArr, 'probability');
        //概率数组的总概率精度
        //$proSum = array_sum(array_column($proArr->toArray(), 'probability'));
        $proSum = array_sum(array_column($proArr, 'probability'));
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, intval($proSum));
            //return $randNum <= $proCur['probability'];
            if ($randNum <= $proCur['probability']) {
                //$result = $key;
                $result = $proCur['id'];
                break;
            } else {
                $proSum -= $proCur['probability'];
            }
        }
        unset ($proArr);

        return $result;
    }

    /**
     * 获取抽奖次数
     * @return false|string
     */
    public function getNumber()
    {
        $vipcode = Request::param('vipcode');

        $rs = Db::connect('zs')->table('member_plug_draw_set')->where('id', 1)->find();
        $number = $rs['number']; //次数
        if(!$vipcode || !$rs || $number<=0){
            return 0;
        }
        //查询已经抽取次数 member_luck_log,luckname,set_id
        $list = Db::connect('zs')->table("member_luck_log")->where(['vipcode'=>$vipcode,'set_id'=>3])->count();

        if($number>$list){
            return $number;
        }else{
            return 0;
        }
    }
    /**
     * 写入抽奖记录
     * @return false|string
     */
    public function setNumber()
    {
        $vipcode = Request::param('vipcode');
        $mobile = Request::param('mobile');
        $set_id = Request::param('set_id');
        $luck = Request::param('luck');
        $openid = Request::param('openid');
        $byteopenid = Request::param('byteopenid') ?: '';
        // set_id_field 值默认是3，也就是写入log表字段set_id默认是3
        $set_id_field = Request::param('set_id_field') ?: 3;
        //$vipcode = '000001142811';

        $time = time();
        $today = date('Y-m-d', $time);

        //$res = Db::connect('zs')->table('member_luck_log')->where(['vipcode' => $vipcode,'set_id' => 3])->find();
        //if(!$res){
            $data = ['vipcode' => $vipcode, 'luckname' => $set_id, 'set_id' => $set_id_field, 'luck' => $luck, 'openid' => $openid, 'byteopenid' => $byteopenid];
            $rs = Db::connect('zs')->table("member_luck_log")->insert($data);
        //}else{
            //$rs = 0;
        //}

        $this->drawNumUsed($vipcode, $today);

        $draw_num_wait = $this->drawNumWait($vipcode, $today);
        return jsonData(1, 'ok', compact('draw_num_wait'));
    }

    /**
     * 中奖记录
     */
    public function rewardLog()
    {
        $vipcode = Request::param('vipcode');
        // $vipcode = '000001084488';
        $mobile = Request::param('mobile');
        $project_type = Request::param('project_type') ?: 3;

        $list_log = Db::connect('zs')->table("member_luck_log")
            ->where('vipcode', $vipcode)
            ->where('set_id', $project_type)
            ->order('id', 'asc')
            ->select();

        if ($list_log->isEmpty()) {
            $rewardLogText = '<p class="text-center">无中奖记录</p>';
            return jsonData(1, 'ok', compact('rewardLogText'));
        }

        $luck_id_arr = $list_log->column('luckname');
        $list_draw_rel = ZsMemberPlugDraw::whereIn('id', $luck_id_arr)->column('*', 'id');

        $list = [];
        $key = 1;
        foreach ($list_log as $item_log) {
            $title = $list_draw_rel[$item_log['luckname']]['title'] ?? '';
            if (empty($title)) {
                continue;
            }
            $list[] = "<p class='m-p-b-10'>{$key}、{$title}</p>";
            $key++;
        }

        $rewardLogText = implode('', $list);
        return jsonData(1, 'ok', compact('rewardLogText'));
    }

    /**
     * 满额领券列表
     */
    public function fullList()
    {
        // 满额领券的项目设置为 11
        $project_type = 11;
        $vipcode = Request::param('vipcode');

        $list = Db::connect('zs')->table("member_plug_draw")
            ->field('title,background,text,top,imgs,id,luck,amount_full')
            ->where(['project_type' => $project_type, 'status' => 1])
            ->select();

        $luck_arr = $list->column('luck');
        $list_coupon = ZsMemberCoupon::whereIn('tid', $luck_arr)->column('*', 'tid');
        $user_has_provide = $this->todayUserProvideArr($project_type, $vipcode);

        $list = $list->toArray();
        foreach ($list as &$item) {
            $curr_tid = $item['luck'];
            $curr_coupon = $list_coupon[$curr_tid] ?? null;
            if (empty($curr_coupon)) {
                continue;
            }

            $item['t_amount'] = $curr_coupon['t_amount'];
            $item['coupon_id'] = $curr_coupon['id'];
            $item['copupon_start_time'] = $curr_coupon['start_time'];
            $item['copupon_end_time'] = $curr_coupon['end_time'];
            $item['copupon_go_time'] = $curr_coupon['go_time'];
            $item['copupon_off_time'] = $curr_coupon['off_time'];

            $item['status_btn_able'] = true;
            $item['status_btn_text'] = '免费领取';

            if (in_array($item['id'], $user_has_provide)) {
                $item['status_btn_able'] = false;
                $item['status_btn_text'] = '今天已领';
            } elseif ($this->couponSoldout($curr_tid, $curr_coupon['number'])) {
                $item['status_btn_able'] = false;
                $item['status_btn_text'] = '券已领完';
            } elseif ($this->todayUserConsumeMax($vipcode) < 300) {
                // $item['status_btn_able'] = false;
                // $item['status_btn_text'] = '消费未达条件';
            }

            $amount_full = $item['amount_full'];
            $amount_full = round($amount_full > 0 ? $amount_full : 0, 2);
            $item['provide_condition'] = $amount_full > 0 ? ('百货/异业单笔消费满' . $amount_full . '元') : '';
            $item['rest_num'] = $curr_coupon['number'] - $this->couponSaleNum($curr_tid);
            $item['rest_num'] = max(0, $item['rest_num']);
        }
        unset($item);
        return jsonData(1, 'ok', compact('list'));
    }

    /**
     * 满额券领取
     */
    public function fullProvide()
    {
        $vipcode = Request::param('vipcode');
        $tid = Request::param('tid');
        $set_id = Request::param('set_id');
        $luck = Request::param('luck');
        $openid = Request::param('openid');
        $byteopenid = Request::param('byteopenid') ?: '';
        // set_id_field 值默认是3，也就是写入log表字段set_id默认是3
        $set_id_field = Request::param('set_id_field') ?: 3;

        if (empty($vipcode) || $vipcode == 'undefined') {
            return jsonData(0, '请先登录');
        }

        if (!$this->checkDraw($set_id)) {
            return jsonData(0, '奖品不存在，请联系王府井工作人员解决');
        }

        if ($this->fullCheckProvideAct($set_id_field, $vipcode, $set_id)) {
            return jsonData(0, '活动期间已经领过赠券，请勿重复领取！');
        }
        // if ($this->fullCheckProvide($set_id_field, $vipcode, $set_id)) {
        //     return jsonData(0, '今天已经领过赠券，请勿重复领取！');
        // }

         $item_coupon = $this->getMemberCoupon($tid);
        if (empty($item_coupon)) {
            return jsonData(0, '券不存在，请联系王府井工作人员解决');
        }

        if (!$this->fullCheckProvideLevel($tid, $vipcode)) {
            return jsonData(0, '会员等级不满足领取条件，不能领取！');
        }

        if (!$this->couponCheckTime($tid)) {
            return jsonData(0, '超出领取时间范围，不能领取！');
        }

        if ($this->couponSoldout($tid, $item_coupon['number'])) {
            return jsonData(0, '抱歉，券已经领完！');
        }
        if ($item_coupon['buy_max'] >= 1 && $this->couponSoldoutByUser($tid, $vipcode, $item_coupon['buy_max'])) {
            return jsonData(0, '抱歉，不能超出限制领取数量！');
        }

        $model_draw = $this->getDraw($set_id);
        $amount_full = $model_draw['amount_full'];
        // $amount_full = $amount_full > 0 ? $amount_full : 300;
        $amount_full = is_numeric($amount_full) ? $amount_full : 300;
        if ($this->todayUserConsumeMax($vipcode) < $amount_full) {
            return jsonData(0, '单笔消费未满足条件！');
        }

        $couponRepository = new CouponRepository();
        $valid_time = $couponRepository->couponValidTime($tid);

        //商家券
        $array = [
            'tid' => $tid,
            'uid' => $vipcode,
            'type' => 0,
            'status' => 0,
            'valid_start' => $valid_time['valid_start'],
            'valid_end' => $valid_time['valid_end'],
        ];
        Db::connect('zs')->table("member_coupon_provide")->insert($array);

        // 科传券
        if ($item_coupon['is_kc'] == 1) {
            $ticket = UserService::VipGetTicket($vipcode,$item_coupon['tid']);
            $errmsg = $ticket->Header->errmsg;
            $errcode = $ticket->Header->errcode;

            UserService::ticketLog($vipcode,$item_coupon['tid'],$errcode,$errmsg); //写入日志
        }

        $data = [
            'vipcode' => $vipcode,
            'luckname' => $set_id,
            'set_id' => $set_id_field,
            'luck' => $luck,
            'openid' => $openid,
            'byteopenid' => $byteopenid,
            'ticketid' => $tid,
        ];
        $rs = Db::connect('zs')->table("member_luck_log")->insert($data);

        $res_data = [
            'status_btn_able' => false,
            'status_btn_text' => '领取成功',
        ];
        return jsonData(1, '领取成功，请到【我的】【优惠券】查看使用！', compact('res_data'));
    }



    /**
     * 新人领券列表
     */
    public function newerList()
    {
        // 新人领券的项目设置为 12
        $project_type = 12;
        $vipcode = Request::param('vipcode');

        $list = Db::connect('zs')->table("member_plug_draw")
            ->field('title,background,text,top,imgs,id,luck,amount_full')
            ->where(['project_type' => $project_type, 'status' => 1])
            ->select();

        $luck_arr = $list->column('luck');
        $list_coupon = ZsMemberCoupon::whereIn('tid', $luck_arr)->column('*', 'tid');
        $user_has_provide = $this->todayUserProvideArr($project_type, $vipcode);

        $list = $list->toArray();
        foreach ($list as &$item) {
            $curr_tid = $item['luck'];
            $curr_coupon = $list_coupon[$curr_tid] ?? null;
            if (empty($curr_coupon)) {
                continue;
            }

            $item['t_amount'] = $curr_coupon['t_amount'];
            $item['coupon_id'] = $curr_coupon['id'];
            $item['copupon_start_time'] = $curr_coupon['start_time'];
            $item['copupon_end_time'] = $curr_coupon['end_time'];
            $item['copupon_go_time'] = $curr_coupon['go_time'];
            $item['copupon_off_time'] = $curr_coupon['off_time'];

            $item['status_btn_able'] = true;
            $item['status_btn_text'] = '免费领取';

            if (in_array($item['id'], $user_has_provide)) {
                $item['status_btn_able'] = false;
                $item['status_btn_text'] = '今天已领';
            } elseif ($this->couponSoldout($curr_tid, $curr_coupon['number'])) {
                $item['status_btn_able'] = false;
                $item['status_btn_text'] = '券已领完';
            } elseif ($this->todayUserConsumeMax($vipcode) < 300) {
                // $item['status_btn_able'] = false;
                // $item['status_btn_text'] = '消费未达条件';
            }

            $item['provide_condition'] = '限新用户当天领取';
            $item['rest_num'] = $curr_coupon['number'] - $this->couponSaleNum($curr_tid);
            $item['rest_num'] = max(0, $item['rest_num']);
        }
        unset($item);
        return jsonData(1, 'ok', compact('list'));
    }

    /**
     * 满额券领取
     */
    public function newerProvide()
    {
        $vipcode = Request::param('vipcode');
        $tid = Request::param('tid');
        $set_id = Request::param('set_id');
        $luck = Request::param('luck');
        $openid = Request::param('openid');
        $byteopenid = Request::param('byteopenid') ?: '';
        // set_id_field 值默认是3，也就是写入log表字段set_id默认是3
        $set_id_field = Request::param('set_id_field') ?: 3;

        if (empty($vipcode) || $vipcode == 'undefined') {
            return jsonData(0, '请先登录');
        }

        if (!$this->checkDraw($set_id)) {
            return jsonData(0, '奖品不存在，请联系王府井工作人员解决');
        }

        if ($this->newerCheckProvide($set_id_field, $vipcode, $set_id)) {
            return jsonData(0, '今天已经领过赠券，请勿重复领取！');
        }

        $item_coupon = $this->getMemberCoupon($tid);
        if (empty($item_coupon)) {
            return jsonData(0, '券不存在，请联系王府井工作人员解决');
        }

        if (!$this->couponCheckTime($tid)) {
            return jsonData(0, '超出领取时间范围，不能领取！');
        }

        if ($this->couponSoldout($tid, $item_coupon['number'])) {
            return jsonData(0, '抱歉，券已经领完！');
        }

        if (!$this->checkNewer($vipcode)) {
            return jsonData(0, '不是新会员，无法领取');
        }

        $couponRepository = new CouponRepository();
        $valid_time = $couponRepository->couponValidTime($tid);

        //商家券
        $array = [
            'tid' => $tid,
            'uid' => $vipcode,
            'type' => 0,
            'status' =>  0,
            'valid_start' => $valid_time['valid_start'],
            'valid_end' => $valid_time['valid_end'],
        ];
        Db::connect('zs')->table("member_coupon_provide")->insert($array);

        // 科传券
        if ($item_coupon['is_kc'] == 1) {
            $ticket = UserService::VipGetTicket($vipcode,$item_coupon['tid']);
            $errmsg = $ticket->Header->errmsg;
            $errcode = $ticket->Header->errcode;

            UserService::ticketLog($vipcode,$item_coupon['tid'],$errcode,$errmsg); //写入日志
        }

        $data = [
            'vipcode' => $vipcode,
            'luckname' => $set_id,
            'set_id' => $set_id_field,
            'luck' => $luck,
            'openid' => $openid,
            'byteopenid' => $byteopenid,
            'ticketid' => $tid,
        ];
        $rs = Db::connect('zs')->table("member_luck_log")->insert($data);

        $res_data = [
            'status_btn_able' => false,
            'status_btn_text' => '领取成功',
        ];
        return jsonData(1, '领取成功，请到【我的】【优惠券】查看使用！', compact('res_data'));
    }

    /**
     * 电子券的使用说明
     */
    public function getIntro()
    {
        $tid = Request::param('tid');

        $coupon = $this->getMemberCoupon($tid);
        if (empty($coupon)) {
            return jsonData(0, '领取使用说明没有找到');
        }

        $text = $coupon->rule;
        return jsonData(1, 'ok', compact('text'));
    }

    /**
     * 分享标题及图片
     */
    public function getShare()
    {
        $data = [
            'title' => '会员礼-王府1卡',
            'imageUrl' => '',
        ];
        return jsonData(1, 'ok', compact('data'));
    }

    public function subList()
    {
        $list = [
            ['name' => '新人礼',],
            ['name' => '满额礼',],
            ['name' => '满额抽',],
        ];
        return jsonData(1, 'ok', compact('list'));
    }

    /**
     * 满额券今天是否已经领取过
     *
     * @param int $project_type 项目
     * @param string $vipcode 会员号
     * @param string $luckname 奖品id
     * @return bool
     */
    private function fullCheckProvide($project_type, $vipcode, $luckname)
    {
        $today = date('Y-m-d');
        $where  = [
            'set_id' => $project_type,
            'vipcode' => $vipcode,
            // 'luckname' => $luckname,
        ];
        $count = Db::connect('zs')->table("member_luck_log")
            ->where($where)
            ->whereLike('create_at', $today.'%')
            ->count();
        return boolval($count);
    }

    /**
     * 满额券活动期间是否已经领取过
     *
     * @param int $project_type 项目
     * @param string $vipcode 会员号
     * @param string $luckname 奖品id
     * @return bool
     */
    private function fullCheckProvideAct($project_type, $vipcode, $luckname)
    {
        $today = date('Y-m-d');
        $where  = [
            'set_id' => $project_type,
            'vipcode' => $vipcode,
            // 'luckname' => $luckname,
        ];
        $count = Db::connect('zs')->table("member_luck_log")
            ->where($where)
            // ->whereBetweenTime('create_at', '2022-03-01', '2022-03-08')
            // ->whereBetweenTime('create_at', '2022-03-16', '2022-03-16')
            // ->whereBetweenTime('create_at', '2022-06-01', '2022-06-30')
            // ->whereBetweenTime('create_at', '2022-07-23', '2022-08-07')
            // ->whereBetweenTime('create_at', '2022-08-04', '2022-08-08')
            ->whereBetweenTime('create_at', '2022-09-09 00:00:00', '2022-09-25 23:59:59')
            ->count();
        return boolval($count);
    }


    /**
     * 满额券活动限制会员等级
     *
     * @param string $tid
     * @param string $vipcode
     * @return bool
     */
    private function fullCheckProvideLevel($tid, $vipcode)
    {
        $data = Db::connect('zs')->table('member_meal')->where('vipcode', $vipcode)->find();
        $grade = strtoupper($data['grade'] ?? '');

        // $v3_tid_arr = ['D310202204140948185098'];
        // $v4_tid_arr = ['D310202204140944195199'];
        $v3_tid_arr = ['D279202207111346359853'];
        $v4_tid_arr = ['D310202207111203091001'];
        if (in_array($tid, $v4_tid_arr)) {
            return in_array($grade, ['V4']);
        } elseif (in_array($tid, $v3_tid_arr)) {
            return in_array($grade, ['V3']);
        }
        return true;
    }
    public function testfullCheckProvideLevel()
    {
        // $tid = 'D310202204140948185098';
        // $vipcode = '000001122653'; // v2

        // $tid = 'D310202204140948185098';
        // $vipcode = '1015024256'; // v3

        // $tid = 'D310202204140944195199';
        // $vipcode = '1015024256'; // v3

        // $tid = 'D310202204140954145457';
        // $vipcode = '1015024256'; // v3

        $tid = 'D310202204140954145457';
        $vipcode = '000001122653'; // v2

        $va = $this->fullCheckProvideLevel($tid, $vipcode);
        var_dump($va);
    }

    /**
     * 新人券今天是否已经领取过
     *
     * @param int $project_type 项目
     * @param string $vipcode 会员号
     * @param string $luckname 奖品id
     * @return bool
     */
    private function newerCheckProvide($project_type, $vipcode, $luckname)
    {
        $today = date('Y-m-d');
        $where  = [
            'set_id' => $project_type,
            'vipcode' => $vipcode,
            'luckname' => $luckname,
        ];
        $count = Db::connect('zs')->table("member_luck_log")->where($where)->whereLike('create_at', $today.'%')->count();
        return boolval($count);
    }

    /**
     * 券是否已经领完
     *
     * @param string $tid
     * @param int $max
     * @return bool
     */
    private function couponSoldout($tid, $max)
    {
        $count = $this->couponSaleNum($tid);
        return $count >= $max;
    }

    /**
     * 券是否已经领完-用户
     *
     * @param string $tid
     * @param string $uid
     * @param int $max
     * @return bool
     */
    private function couponSoldoutByUser($tid, $uid, $max)
    {
        $count = $this->couponSaleNumByUser($tid, $uid);
        return $count >= $max;
    }

    /**
     * 判断领券时间是否有效
     *
     * @param string $tid
     * @return bool
     */
    private function couponCheckTime($tid)
    {
        $time_str = timeStr();

        $coupon = $this->getMemberCoupon($tid);
        return $coupon && $time_str >= $coupon['go_time'] && $time_str <= $coupon['off_time'];
    }

    /**
     * 券领取张数
     *
     * @param string $tid
     * @return int
     */
    private function couponSaleNum($tid)
    {
        return ZsMemberCouponProvide::where('tid', $tid)->where('status', '<', 3)->count();
    }

    /**
     * 券领取张数-用户
     *
     * @param string $tid
     * @param string $uid
     * @return int
     */
    private function couponSaleNumByUser($tid, $uid)
    {
        return ZsMemberCouponProvide::where('tid', $tid)->where('uid', $uid)->where('status', '<', 3)->count();
    }

    /**
     * 查询出用户当天在百货或者异业最大的单笔消费金额
     *
     * @param string $vipcode
     * @return float
     */
    private function todayUserConsumeMax($vipcode)
    {
        $startDate = date('Y-m-d 00:00:00');
        $endDate = date('Y-m-d 23:59:59');

        $saleList = ZsnewKcSale::where('XF_VIPCODE', $vipcode)
            ->whereBetweenTime('XF_CREATETIME', $startDate, $endDate)
            ->select();
        $max = 0;
        foreach ($saleList as $saleItem) {
            if ($saleItem['btype'] == 2 || $saleItem['btype'] == 3) {   // 百货或者异业
            // if ($saleItem['btype'] == 1 || $saleItem['btype'] == 2 || $saleItem['btype'] == 3) {   // 美食或者百货或者异业
                $max = max($saleItem['XF_SELLINGAMOUNT'], $max);
            }
        }
        return $max;
    }

    /**
     * 判断用户是否新会员
     *
     * @param string $vipcode
     * @return bool
     */
    private function checkNewer($vipcode)
    {
        $today = date('Y-m-d');
        $model = ZsMemberMeal::where('vipcode', $vipcode)->find();
        return $model && strpos($model->create_at, $today) !== false;
    }

    /**
     * 查询用户今天已领取的奖品ID数组
     *
     * @param int $project_type
     * @param string $vipcode
     * @return array
     */
    private function todayUserProvideArr($project_type, $vipcode)
    {
        $today = date('Y-m-d');
        $where  = [
            'set_id' => $project_type,
            'vipcode' => $vipcode,
        ];
        $arr = Db::connect('zs')->table("member_luck_log")->where($where)->whereLike('create_at', $today.'%')->column('luckname');
        return $arr;
    }

    /**
     * 获取奖品记录
     *
     * @param int $id
     * @return ZsMemberPlugDraw
     */
    private function getDraw($id)
    {
        return ZsMemberPlugDraw::find($id);
    }

    /**
     * 奖品是否存在，并且启用状态
     *
     * @param int $id
     * @return bool
     */
    private function checkDraw($id)
    {
        $model = $this->getDraw($id);
        return $model && $model->status = 1;
    }

    /**
     * 查询电子券
     *
     * @param string $tid
     * @return ZsMemberCoupon
     */
    private function getMemberCoupon($tid)
    {
        return ZsMemberCoupon::where('tid', $tid)->find();
    }
}
